define(function() {
	var vectorLayer, handlerDis, handlerArea, handlerHeight, handlerShadow, shadowQuery, skyline, handlerLimitBody, handlerViewPoint, sightline, pointHandler, viewshed3D, slope, wide, handlerPolygon;
	var viewModel,handler,handler3Dto2D,toolbar,MaptoScene;
	var flylayer = [];


	//函数：获取尺寸
	function _autodivheight() { 
		//获取浏览器窗口高度
		var winHeight = 0;
		if (window.innerHeight) winHeight = window.innerHeight;
		else if ((document.body) && (document.body.clientHeight)) winHeight = document.body.clientHeight;
		//通过深入Document内部对body进行检测，获取浏览器窗口高度
		if (document.documentElement && document.documentElement.clientHeight) winHeight = document.documentElement.clientHeight;
		//DIV高度为浏览器窗口的高度
		//document.getElementById("test").style.height= winHeight +"px";
		//DIV高度为浏览器窗口高度的一半
		if (document.getElementById("content")) document.getElementById("content").style.height = (winHeight - 100) + "px";
		if (document.getElementById("left")) document.getElementById("left").style.height = (winHeight - 100) + "px";
		if (document.getElementById("right")) document.getElementById("right").style.height = (winHeight - 100) + "px";		
		if (document.getElementById("mapDiv")) document.getElementById("mapDiv").style.height = (winHeight - 132) + "px";
	}

	
	//clear清除
	function Flyclear(){
		//清除2维联动3维开关
		flylayer[0].events.un({
			"moveend": MaptoScene
		});
	}

	//二三维图层控制 三维图层控制
	function _ThreeLayer(layer){
		for (var i = 0; i < layer.length; i++) { 
			layer[i].visible = false; 
		} 	
		console.log(layer);	
		//默认显示 [建筑面、树、遥感影像、数字高程、水面、地形、行政中心方案]
		layer[5].visible = true;
		layer[1].visible = true;
		layer[6].visible = true;
		layer[9].visible = true;
		layer[4].visible = true;
		layer[4].visible = true;
		layer[4].visible = true;
	}

	//二三维图层控制 二维图层控制
	function _twoThree(urlPingyin) {
		//start loading to map
	    var urlPingyinMax = urlPingyin.length-1;
	    var flylayerClassName = new Array('底图','地形图','ZG用地规划','ZG市政规划','ZG防灾景观规划','修建性规划','居住统计','条件方案地块');
		
		//坐标转换: 2384 -> 4326
		proj4.defs('EPSG:2384' , "+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs");
		var newProj = ol.proj.get('EPSG:2384');
		var proj4326 = ol.proj.get('EPSG:4326');

		//map
		map = new SuperMap.Map("mapContainer", {
	        controls: [
	            new SuperMap.Control.Zoom(),
	            new SuperMap.Control.Navigation({
	                dragPanOptions: {
	                    enableKinetic: true
	                }
	            })], 
	        allOverlays: true
	    });
		
		//相关地图的默认显示
		function defaultShowFly(){
			var defaultShowAction = $('#result>.TreeAutoCreate');
			$(defaultShowAction).eq(1).find('input').removeAttr('checked');
			$(defaultShowAction).eq(3).find('input').removeAttr('checked');
			$(defaultShowAction).eq(4).find('input').removeAttr('checked');
			$(defaultShowAction).eq(5).find('input').removeAttr('checked');
			$(defaultShowAction).eq(6).find('input').removeAttr('checked');
			$(defaultShowAction).eq(7).find('input').removeAttr('checked');
			//
			flylayer[1].setVisibility(false);
			flylayer[1].redraw();
			flylayer[3].setVisibility(false);
			flylayer[3].redraw();
			flylayer[4].setVisibility(false);
			flylayer[4].redraw();
			flylayer[5].setVisibility(false);
			flylayer[5].redraw();
			flylayer[6].setVisibility(false);
			flylayer[6].redraw();
			flylayer[7].setVisibility(false);
			flylayer[7].redraw();
			//
			flylayer[0].setVisibility(true); 
			flylayer[0].redraw(); 
			flylayer[2].setVisibility(true); 
			flylayer[2].params.layersID = "[0:0,1,2]"; 
			flylayer[2].redraw(); 
		}



	    /**
	     * 加载地图图层信息   [针对图层的全部操作]
	     * 整体逻辑依次循环   [单次循环后才执行下一次循环]
	     */
		loadMapInfo();
	   	function loadMapInfo (){

	   		//init-自我循环使用
	   		var urlPingyinThisNum = 0;

			//加载地图图层信息
			getLayersMapInfoFly();
	   		function getLayersMapInfoFly(){
	   			var getLayersInfoService = new SuperMap.REST.GetLayersInfoService(urlPingyin[urlPingyinThisNum]);
				getLayersInfoService.events.on({
					"processCompleted": getLayersInfoCompleted
				});
				getLayersInfoService.processAsync();
	   		}

			//与服务器交互成功，得到子图层信息
			function getLayersInfoCompleted(getLayersInfoEventArgs) {
				var subLayers = {};
				if (getLayersInfoEventArgs.result) {
					if (getLayersInfoEventArgs.result.subLayers) {
						subLayers = sub_layer(getLayersInfoEventArgs.result,'first');
					}
				}
				installPanel(subLayers);
			}

		    //obj传入类; typeOrNum传入first或num字符串  (---辅助加载二级图层---)
			function sub_layer(obj,typeOrNum){ 
				var info = {}; 
				info.name = obj.caption; 
				if(typeOrNum=='first'){ 
					info.name = obj.name; 
					info.layerID = urlPingyinThisNum; 
				}else{ 
					info.name = obj.caption; 
					info.layerID = typeOrNum; 
				} 
				info.visible = obj.visible;
				if(typeof obj.subLayers.layers != 'undefined'){
	 				var layer_count = obj.subLayers.layers.length;
					var nodes = [];
					for (var i=0; i < layer_count; i++) {
						var node = sub_layer(obj.subLayers.layers[i],i); 
						nodes.push(node);
					}
					info.lists = nodes;
				}else{
					info.lists = false;
				}
				return info;
			}

			//内容加载至html代码中.
			var TextString = "";
			function forTreeHtml(data) {
				for(var i=data.length-1; i>=0; i--) {
					var urlstr = "";
					if (data[i]["lists"] == false) {
						urlstr = "<div class='TreeAutoCreate' thisid='" + data[i]["layerID"] + "' ><span><input type='checkbox' checked='checked'> <a href='#'>" + data[i]["name"] + "</a></span><ul style='display:block;'>";
					} else {
						urlstr = "<div class='TreeAutoCreate' thisid='" + data[i]["layerID"] + "' ><span><input type='checkbox' checked='checked'> <a href='#'>" + data[i]["name"] + "</a></span><ul style='display:none;'>";
					}
					TextString += urlstr;
					if (data[i]["lists"] != false) {
						forTreeHtml(data[i]["lists"]);
					}
					TextString += "</ul></div>";
				}
				return TextString;
			}

			//组装操作面板，显示子图层列表，并初始化地图显示, 事件的绑定.
			function installPanel(subLayers) {
				//先进行html加载.
				TextString = "";
				var LayerAllHtmlFly = forTreeHtml([subLayers]);
				$('#result').append(LayerAllHtmlFly);
				createTempLayer();
			}

			//获取当前地图子图层状态信息
		    function getLayerStatusList(parameters) {
		        var layersList = $(".TreeAutoCreate");
		        for (var i = 0; i < layersList.length; i++) {
		            var layerStatus = new SuperMap.REST.LayerStatus();
		            layerStatus.layerName = $(layersList[i]).find('a').html();
		            layerStatus.isVisible = true;
		            parameters.layerStatusList.push(layerStatus);
		        }
		        //设置资源在服务端保存的时间，单位为分钟，默认为10
		        parameters.holdTime = 30;
		        return parameters;
		    }

			//创建临时图层来初始化当前地图显示
		    function createTempLayer() {
		        //子图层控制参数必设：url、mapName、SetLayerStatusParameters
		        var layerStatusParameters = new SuperMap.REST.SetLayerStatusParameters();
		        layerStatusParameters = getLayerStatusList(layerStatusParameters);

		        var setLayerStatusService = new SuperMap.REST.SetLayerStatusService(urlPingyin[urlPingyinThisNum]);
		        setLayerStatusService.events.on({"processCompleted": addLayer});
		        setLayerStatusService.processAsync(layerStatusParameters);
		    }

		    //自我循环添加完成全部layer
		    function addLayer(createTempLayerEventArgs) {
	        	tempLayerID = createTempLayerEventArgs.result.newResourceID;
		        flylayer[urlPingyinThisNum] = new SuperMap.Layer.TiledDynamicRESTLayer(flylayerClassName[urlPingyinThisNum], urlPingyin[urlPingyinThisNum], {
		            transparent: true,
		            cacheEnabled: false,
		            redirect: true,
		            layersID: tempLayerID
		        });
		        flylayer[urlPingyinThisNum].bufferImgCount = 0;

		        if(urlPingyinThisNum==urlPingyinMax){
		            flylayer[urlPingyinThisNum].events.on({"layerInitialized": addLayerOk});
		        } else {
		        	flylayer[urlPingyinThisNum].events.on({"layerInitialized": getLayersMapInfoFly});
		        }
		        flylayer[urlPingyinThisNum].setOpacity(0.8);
				urlPingyinThisNum++;
		    }

		    //添加完成最后调用
		    function addLayerOk() {
		        map.addLayers(flylayer);
		        var supermapLonLatChange = new SuperMap.LonLat(451343.84 , 4017036.9);
		        map.setCenter(supermapLonLatChange, 4); //zoom: 14
				//默认相关地图的显隐
				defaultShowFly();
		    }

			//绑定-打开图层开关.
			$('#layerBtn').click(function(){
				if($('#resultDiv').css('display')=='none'){
					$('#resultDiv').fadeIn(200);
				} else {
					$('#resultDiv').fadeOut(200);
				}
			});

			//绑定-点开某个上级打开下级
			$('body').on('click', '.TreeAutoCreate a', function(){
				var thisUl = $(this).parent().next();
				if(thisUl.css('display')=='none'){
					thisUl.show();
				} else {
					thisUl.hide();
				}
			});

			//点击多选框选择
			$('#result').on('click', 'input', function(){
				var thisUpDiv = $(this).parent().parent();
				if($(this).is(':checked')){
					thisUpDiv.find('input').prop("checked", true);
					thisUpDiv.find('input').attr("checked", "checked");
				} else {
					thisUpDiv.find('input').prop("checked", false);
					thisUpDiv.find('input').removeAttr('checked');
				}
				setLayerStatus(this);
			});

			// 子图层可见性控制
			// 文献：http://support.supermap.com.cn:8090/iserver/help/html/zh/mergedProjects/SuperMapiServerRESTAPI/root/maps/map/tileImage.htm#GET%E8%AF%B7%E6%B1%82
			function setLayerStatus(othis) {
				//获取最上层
				var parentTreeAutoCreate = $(othis).parents('.TreeAutoCreate:last');
				var AllTreeAutoCreate = parentTreeAutoCreate.find('.TreeAutoCreate');
				var result = []; 
				//获取当前操作的地图字符串
				result.mapnameID = parentTreeAutoCreate.attr('thisid');
				//获取拼接后的字符串
				var AlllayerString = "[0:"; 
				var pre = ""; 
				var truefalse = false; 
				for(var i=AllTreeAutoCreate.length; i>=0; i--){ 
					var thisTreeEqVal = AllTreeAutoCreate.eq(i); 
					if(thisTreeEqVal.find('.TreeAutoCreate').length<1){  //只获取最底层图层
						if(thisTreeEqVal.find('input:first').is(':checked')){  //被选定状态进行操作
							var thisid = thisTreeEqVal.attr('thisid'); 
							//判断有上级则进行字符串拼接 
							var thisupid = UpParentsToString(thisTreeEqVal); 
							AlllayerString += pre + thisupid + thisid; 
							pre = ","; 
							truefalse = true; 
						} 
					} 
				} 
				AlllayerString += "]"; 
				result.str = AlllayerString;  
				//判断truefalse为真则显示，否则隐藏。  
				if(truefalse){  
					//通过TiledDynamicRESTLayer的属性layersID来控制子图层的可见性，推荐使用此方法 
					flylayer[result.mapnameID].setVisibility(true);
					flylayer[result.mapnameID].params.layersID = result.str; 
				} else { 
					flylayer[result.mapnameID].params.layersID = "[]"; 
					flylayer[result.mapnameID].setVisibility(false);
				} 
				flylayer[result.mapnameID].redraw(); 
			} 
			//判断有上级则进行字符串拼接  [子图层控制辅助函数]
			function UpParentsToString(thisTreeEqVal){
				var parentTreeAutoCreates = thisTreeEqVal.parents('.TreeAutoCreate');
				//othis = input
				if(parentTreeAutoCreates.length>1){
					var result = pre = "";
					for(var i=parentTreeAutoCreates.length-2; i>=0; i--){
						result += pre + parentTreeAutoCreates.eq(i).attr('thisid');
						pre = ".";
					} 
					return result+'.';
				} else {
					return "";
				}
			}
	   	}

		//三维监听事件
        handler3Dto2D = new Cesium.ScreenSpaceEventHandler(scene.canvas);

		//二维联动三维
		$("#Explore3D").click(function() {


			//alert("ddsfsdfsf");


			mapPan();
		});

		//三维联动二维
		$("#Explore2D").click(function() {
			scenePan();
		});

		//辅助下方操作
		MaptoScene = function() {
			//获取相应数据
			var info = ConversionEPSGfly();
			//设置场景相机
			viewer.scene.camera.setView({
				destination: new Cesium.Cartesian3.fromDegrees(info.lon, info.lat, info.altitude)
			});

				//alert("1");
			// var supermapLonLatChange = new SuperMap.LonLat(451343.84 , 4017036.9);
	  //       map.setCenter(supermapLonLatChange, 4); //zoom: 14
	        //alert("2");	


		}

		//二维联动三维
		mapPan = function() {
			//添加地图监听事件
			flylayer[0].events.on({
				"moveend": MaptoScene
			});

			
			//移除场景鼠标事件
			// handler3Dto2D.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
			// handler3Dto2D.removeInputAction(Cesium.ScreenSpaceEventType.WHEEL);
		};

		//三维联动二维
		//var counti = 0.1;
		scenePan = function() {


 			// var supermapLonLatChange = new SuperMap.LonLat(451343.84 , 4017036.9);
		  	//       map.setCenter(supermapLonLatChange, 4); //zoom: 14	

			//注销地图监听事件
			//flylayer[0].events.unregister("moveend", undefined, MaptoScene);
			handler3Dto2D.setInputAction(function(click) {
				console.log("开始测试移动"); 
				var camera = viewer.scene.camera;
				var cameraPosiion = camera.position;
				var cartographic = Cesium.Cartographic.fromCartesian(cameraPosiion);
				var longitude = Cesium.Math.toDegrees(cartographic.longitude);
				var latitude = Cesium.Math.toDegrees(cartographic.latitude);
				var height = cartographic.height;
				var size = _calculateSizeFromAltitude(height);
				size = size * 0.3;
				// var rect = viewer.camera.computeViewRectangle(viewer.scene.globe.ellipsoid,rect);
				// console.log("west:"+rect.west);
				// console.log("south"+rect.south);
				// console.log("east"+rect.east);
				// console.log("north"+rect.north);
				//设置地图显示范围
				var bounds = new SuperMap.Bounds(longitude - size, latitude - size, longitude + size, latitude + size);
				//var bounds = new SuperMap.Bounds(longitude - size, latitude - size, longitude + size, latitude + size);
				var resultinfo = ConversionEPSG4326To2384fly(bounds);
				//坐标转换
				var bounds_new = new SuperMap.Bounds(resultinfo[0], resultinfo[1], resultinfo[2], resultinfo[3]);

				map.zoomToExtent(bounds_new, false);
				console.log("转换后的坐标信息为："+resultinfo);
				console.log("结束测试移动");
			},
			Cesium.ScreenSpaceEventType.LEFT_UP);
			//添加场景鼠标事件
			// handler3Dto2D.setInputAction(function(movement) {
			// 	console.log("测试滚轮");
			// 	var camera = viewer.scene.camera;
			// 	var cameraPosiion = camera.position;
			// 	var cartographic = Cesium.Cartographic.fromCartesian(cameraPosiion);
			// 	var longitude = Cesium.Math.toDegrees(cartographic.longitude);
			// 	var latitude = Cesium.Math.toDegrees(cartographic.latitude);
			// 	var height = cartographic.height;
			// 	var size = _calculateSizeFromAltitude(height);
			// 	size = size * 0.5;
			// 	//设置地图显示范围
			// 	var bounds = new SuperMap.Bounds(longitude - size, latitude - size, longitude + size, latitude + size);
				
			// 	//坐标转换

			// 	map.zoomToExtent(bounds, false);
			// },
			// Cesium.ScreenSpaceEventType.WHEEL);
		};
		
		//二维map的viewBoundsChanged事件的回调函数
		function viewBoundsChangedHandler() {
			var viewBounds = map.get_viewBounds();
			var altitude = _calculateAltitudeFromBounds(viewBounds);
			var camera = sceneControl.get_scene().get_camera();
			camera.set_altitude(altitude);
			sceneControl.get_scene().set_camera(camera);
		}

		/// <summary>
		/// 根据给定的地图范围计算场景的高度
		/// </summary>
		/// <param name="bounds">地图范围</param>
		/// <returns>场景高度</returns>
		function _calculateAltitudeFromBounds(bounds) {
			var _PI = 3.1415926;
			var _earthRadius = 6378137;
			var altitude = _earthRadius;
			var boundsWidth = bounds.right - bounds.left;
			if (boundsWidth >= 120) {
				altitude = _earthRadius * boundsWidth / 60 - _earthRadius;
			} else if (boundsWidth != 0) {
				var angle1 = (boundsWidth / 360) * _PI;
				var height = Math.sin(angle1) * _earthRadius;
				var a = height / Math.tan(angle1);
				var b = height / Math.tan(_PI / 6);
				altitude = a + b - _earthRadius;
			}
			return altitude;
		}

		/// <summary>
		/// 根据给定的场景高度计算地图中显示范围的宽度
		/// </summary>
		/// <param name="altitude">场景高度</param>
		/// <returns>地图显示范围尺寸</returns>
		function _calculateSizeFromAltitude(altitude) {
			var _PI = 3.1415926;
			var _earthRadius = 6378137;
			var size;
			if (altitude >= _earthRadius) { //当场景高度大于可全幅显示整球的高度时
				var ratio = (altitude + _earthRadius) * 0.5;
				size = 120 * ratio / _earthRadius
			} else { //当场景高度小于可全幅显示整球的高度时，即无法看到整球时
				var tan30 = Math.tan(_PI / 6);
				//设置方程组的a,b,c
				var a = (Math.pow(tan30, 2) + 1) * Math.pow(_earthRadius, 2);
				var b = -2 * (_earthRadius + altitude) * _earthRadius * Math.pow(tan30, 2);
				var c = Math.pow(tan30, 2) * Math.pow(_earthRadius + altitude, 2) - Math.pow(_earthRadius, 2.0);
				//解一元二次方程，取锐角，因此余弦值较大
				var cosd = ( - b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
				var d = Math.acos(cosd);
				var widthd = 2 * d * _earthRadius;
				size = (widthd / (_PI * _earthRadius)) * 180;
			}
			return size;
		}
		
		// <fly>
		// 坐标系转换   [EPSG:2384 --> EPSG:4326]
		// <returns>EPSG:4326</returns>
		function ConversionEPSGfly(){
			var info = {};
			//获取当前地图范围 
			var bounds = map.getExtent();
			var resultLonLat = ol.proj.transformExtent([bounds.left, bounds.bottom, bounds.right, bounds.top], newProj, proj4326);
			var resultLonLatName = [];
			resultLonLatName['left'] = resultLonLat[0];
			resultLonLatName['bottom'] = resultLonLat[1];
			resultLonLatName['right'] = resultLonLat[2];
			resultLonLatName['top'] = resultLonLat[3];
			//根据给定的地图范围计算场景的高度 
			var altitude = _calculateAltitudeFromBounds(resultLonLatName);
			//获取地图中心点 
			var center = map.getCenter(); 
			var LonLat = ol.proj.toLonLat([center.lon, center.lat], newProj);
			//组装 
			info.lon = IntSubStrFly(LonLat[0]); //经度
			info.lat = IntSubStrFly(LonLat[1]); //纬度
			info.altitude = IntSubStrFly(altitude); //高度
			//返回
			return info; 
		} 

		// <fly>
		// 坐标系转换   [EPSG:4326 --> EPSG:2384]
		// <returns>EPSG:4326</returns>
		function ConversionEPSG4326To2384fly(bounds){

			//坐标转换: 2384 -> 4326
			proj4.defs('EPSG:2384' , "+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=500000 +y_0=0 +a=6378140 +b=6356755.288157528 +units=m +no_defs");
			var newProj = ol.proj.get('EPSG:2384');
			var proj4326 = ol.proj.get('EPSG:4326');
		
			var resultLonLat = ol.proj.transformExtent([bounds.left, bounds.bottom, bounds.right, bounds.top], proj4326, newProj);
			// var resultLonLatName = [];
			// resultLonLatName['left'] = resultLonLat[0];
			// resultLonLatName['bottom'] = resultLonLat[1];
			// resultLonLatName['right'] = resultLonLat[2];
			// resultLonLatName['top'] = resultLonLat[3];
			
			//返回
			return resultLonLat; 
		} 

		// <fly>
		// 截取长度 -小数点后7位
		// <returns>Int</returns>
		function IntSubStrFly(num){
			num = num+"";
			var returnnum = num.substring(0,num.indexOf(".") + 14);
			return parseFloat(returnnum);
		}
	}

	/* 
	 * 条件查询
	 * 查询存在问题，二维数据查询不到； 三维数据提示资源不存在;
	 */
	function _sqlselect(){	
		//init
		var htmlValue = new Array(
			$('#sqlselectText1').val(),
			$('.layui-select-title input').eq(1).val(),
			$('#sqlselectText2').val()
		);	
		var style2d = {
            strokeColor: "#304DBE",
            strokeWidth: 1,
            fillColor: "#304DBE",
            fillOpacity: "0.8"
        };
		//添加二维控制图层 
		var vectorLayer = new SuperMap.Layer.Vector("FlyVectorLayer"); 
		map.addLayer(vectorLayer);  
		//select选择对应操作的图层 
		var thisLayerInfo = getSelectLayer( $('.layui-select-title input').eq(0).val() ); 
		thisLayerInfo.queryParams = thisLayerInfo.parameter + htmlValue[1] + htmlValue[2];

		//清除联动
		Flyclear();

		/************************ 二维 ************************/
		//获取条件查询-所操作的图层ID  [辅助上面查询]
		function getSelectLayer(str){
			var thisLayerInfo = [];
			var thisLayerNum = SqlSelectJson;
			for(var i=0; i<thisLayerNum.length; i++){
				var thisinfo = thisLayerNum[i];
				if(str == thisinfo.showName){
					thisLayerInfo = thisinfo;  //图层名称
				}
			}
			return thisLayerInfo;
		}
		//开始.
		queryBySQL();
	    function queryBySQL() {
	        vectorLayer.removeAllFeatures();
	        var queryParam, queryBySQLParams, queryBySQLService;
	        queryParam = new SuperMap.REST.FilterParameter({
	            name: thisLayerInfo.name,
	            attributeFilter: thisLayerInfo.queryParams
	        });
	        queryBySQLParams = new SuperMap.REST.QueryBySQLParameters({
	            queryParams: [queryParam]
	        }); 
	        queryBySQLService = new SuperMap.REST.QueryBySQLService(thisLayerInfo.url, { 
	            eventListeners: {"processCompleted": processCompleted2, "processFailed": processFailed2} 
	        });
	        queryBySQLService.processAsync(queryBySQLParams); 
	    } 
	    function processCompleted2(queryEventArgs) { 
	        var i, j, feature, 
	            result = queryEventArgs.result; 
	        if (result && result.recordsets) { 
	            for (i = 0; i < result.recordsets.length; i++) { 
	                if (result.recordsets[i].features) { 
	                    for (j = 0; j < result.recordsets[i].features.length; j++) { 
	                        feature = result.recordsets[i].features[j]; 
	                        feature.style = style2d; 
	                        vectorLayer.addFeatures(feature); 
	                    } 
	                } 
	            } 
	        } 
	    } 
	    function processFailed2(e) {
	    	console.log('2维查询失败');
	    	console.log(e);
	    }
	    function clearFeatures2() {
	        //先清除上次的显示结果
	        vectorLayer.removeAllFeatures();
	        vectorLayer.refresh();
	    }
	    
		

		/************************ 三维 ****************************/
		var scene = viewer.scene;
        var widget = viewer.cesiumWidget;
        var IDs=[];
		var querySql = thisLayerInfo.parameter + htmlValue[1] + htmlValue[2];
		doSqlQuery(querySql);
		function onQueryComplete3(queryEventArgs){
		console.log('三维ok');
		console.log(queryEventArgs); 
			//上方添加点
            // var selectedFeatures = queryEventArgs.originResult.features;
            // viewer.entities.removeAll();
            // for(var i = 0;i < selectedFeatures.length;i++ ){
            //     var value = selectedFeatures[i].fieldValues["0"];
            //     var feature = selectedFeatures[i];
            //     for(var j = 0; j < feature.fieldNames.length ; j++){
            //         var index = j.toString();
            //         if(j == 0){
            //              var des = '<table class="cesium-infoBox-defaultTable"><tbody>' + '<tr><th>' + selectedFeatures[i].fieldNames["0"] + '</th><td>' + selectedFeatures[i].fieldValues["0"] + '</td></tr>';
            //         }
            //         else if( j == feature.fieldNames.length - 1){
            //             des += '<tr><th>' + selectedFeatures[i].fieldNames[index] + '</th><td>' + selectedFeatures[i].fieldValues[index] + '</td></tr>' + "</tbody></table>";
            //         }
            //         else{
            //             des += '<tr><th>' + selectedFeatures[i].fieldNames[index] + '</th><td>' + selectedFeatures[i].fieldValues[index] + '</td></tr>';
            //         }
            //     }
            //     viewer.entities.add({
            //         position : Cesium.Cartesian3.fromDegrees(parseFloat(selectedFeatures[i].fieldValues["12"]),parseFloat(selectedFeatures[i].fieldValues["13"]),parseFloat(selectedFeatures[i].fieldValues["16"])),
            //         billboard :{
            //             image : './images/location4.png',
            //             width:30,
            //             height:40
            //         },
            //         name : selectedFeatures[i].fieldValues["11"],
            //         description: des
            //     });
            //     IDs.push(parseInt(value)+11);
            // }
            
            //结果添加
            var buildingLayer = scene.layers.find("Building@CBD");
            if(IDs.length>0){
                buildingLayer.setSelection(IDs);
            }
            //添加阴影
			var selectedFeatures = queryEventArgs.originResult.features;
            for(var i = 0;i < selectedFeatures.length;i++ ){
                var value = selectedFeatures[i].fieldValues["0"];
                IDs.push(parseInt(value)+11);
            }
        }
        function doSqlQuery(SQL){
            var getFeatureParam, getFeatureBySQLService, getFeatureBySQLParams;
            getFeatureParam = new SuperMap.REST.FilterParameter({
                attributeFilter: SQL
            });
            getFeatureBySQLParams = new SuperMap.REST.GetFeaturesBySQLParameters({
                queryParameter: getFeatureParam,
                toIndex : -1,
                datasetNames: ["建筑方案"]
            });
            var url = "http://172.29.1.26:8090/iserver/services/3D-py056/rest/realspace/datas";
            getFeatureBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url, {
                eventListeners: {
                    "processCompleted": onQueryComplete3, 
                    "processFailed": processFailed3
                }
            }); 
            getFeatureBySQLService.processAsync(getFeatureBySQLParams);
        }
        function processFailed3(queryEventArgs){
            console.log('3维查询失败');
            console.log(queryEventArgs);
        }
        /**/
	}
	


	//模糊查询
	//其他位置存放两组数据，便于获取相对应的值，三维/二维打开其位置
	function _VagueSelect(){
		//清除联动
		Flyclear();
		//二维改变位置
		var newAdressInfoTwo = FlyGetSearchInfo('two');
		if(newAdressInfoTwo.status){
			var Flythisbound = new SuperMap.Bounds(newAdressInfoTwo.left, newAdressInfoTwo.bottom, newAdressInfoTwo.right, newAdressInfoTwo.top);
			map.zoomToExtent(Flythisbound, false);
		}
		//三维改变位置
		var newAdressInfoThree = FlyGetSearchInfo('three');
		if(newAdressInfoThree.status){
			scene.camera.setView({
				destination:new Cesium.Cartesian3.fromDegrees(newAdressInfoThree.lon,newAdressInfoThree.lat,newAdressInfoThree.height),
				orientation : {
					heading : 0,
					pitch : 30 
					//方位角(heading)、俯仰角(pitch)
				} 
			});	
		}
		//辅助上方模糊查询功能.
		function FlyGetSearchInfo(type){
			//
			var result = [];
			result.status = false;
			var thisVal = $('#VagueSelectInput').val();
			//
			if (type=='two') { //二维
				for(var i=0; i<TwoThreeAllPoint.two.length; i++){
					if(TwoThreeAllPoint.two[i].name.indexOf(thisVal) > 0 || TwoThreeAllPoint.two[i].name==thisVal){
						result = TwoThreeAllPoint.two[i];
						result.status = true;
					}
				}
			} else { //三维
				for(var i=0; i<TwoThreeAllPoint.three.length; i++){
					if(TwoThreeAllPoint.three[i].name.indexOf(thisVal) > 0 || TwoThreeAllPoint.three[i].name==thisVal){
						result = TwoThreeAllPoint.three[i];
						result.status = true;
					}
				}
			}
console.log(result);			
			return result;
		}
	}
	
	
	
	
	return {
		threelayer: _ThreeLayer,
		autodivheight: _autodivheight,
		twoThree: _twoThree,
		sqlselect: _sqlselect,
		VagueSelect: _VagueSelect
	};
	
	
	
	
});
	